package cn.gov.chinamor.zxing.util;

import org.json.JSONException;
import org.json.JSONObject;

import android.os.Handler;
import android.os.Message;
import cn.gov.chinamor.zxing.listener.OnFinishListener;

public class QueryClient {

	OnFinishListener listener;
	Handler handler;
	HttpThread httpThread;
	Thread thread;
	
	public QueryClient() {
		
	}
	
	public void crawUrl(String url, OnFinishListener ofl) {
		
		this.listener = ofl;
		handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				if (httpThread == null) {
					return;
				}

				if (msg.what == HttpThread.MSG_FINISH) {
					String result = msg.getData().getString(HttpThread.MSG_KEY);
					listener.onFinish(result);
				} else if (msg.what == HttpThread.MSG_ERROR) {
					String result = msg.getData().getString(HttpThread.MSG_KEY);
					JSONObject jo = new JSONObject();
					try {
						jo.put("error", result);
					} catch (JSONException e) {
						e.printStackTrace();
					}
					listener.onFinish(jo.toString());
				}
			}
		};
		
        httpThread = new HttpThread(handler, url);
        thread = new Thread(httpThread);
        thread.start();
	}
}
